package calm.museum;




import java.io.File;

import jenamuseum.annotation.Annotation;
import jenamuseum.annotation.AnnotationBase;
import jenamuseum.annotation.AnnotationList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import annotation.display.videoRecorder;

public class mainActivity extends ListActivity {
    /** Called when the activity is first created. */
	public static final String serverURL = "http://172.26.139.29:8080/";
	public static final String closyURL = "http://172.26.139.29/ClosyInfoUI";
	private String current_user_name;
	private WebView artworkView;
	private String currentartwork;
	private WebView artworkLink;
	private AlertDialog alert1;
	private Button annotationButton;
	private Dialog showAnnotationDialog;
	private Dialog newAnnotationDialog;
	private static RestletAdapter restletAdapter;
	private EditText newAnnotationTitle;
	private EditText newAnnotationBody;
	public String[] object;
	public AnnotationList currentAnnotations;
	final Handler uiHandler = new Handler();
	//TODO Implement annotation posting thread to improve latency
	final Runnable updateResult = new Runnable() {
		
		@Override
		public void run() {
			updateMessage();
			// TODO Auto-generated method stub
			
		}
	};

	private class WebViewClientHandler extends WebViewClient {

		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			  String isDetail = "detail\\/";
			  String isIndex ="inde";
			  Log.w("Loading resource : ",url);
			  Log.w("This is index ", String.valueOf(url.split(isIndex).length));
			  if(url.split(isIndex).length>1)
			  {			  
			    artworkLink.loadUrl(serverURL + "information");
				setListAdapter(new AnnotationArrayAdapter(mainActivity.this, R.layout.row_layout, new AnnotationList() ));		        		
			  }
			  else if (url.split(isDetail).length>1)
			  {		  
					 
				  if(restletAdapter==null){restletAdapter=new RestletAdapter();}
				  object = url.split(isDetail);
				  currentartwork=object[1];
				  Log.w("TESTNULL",object[1].toString());
				  currentAnnotations = restletAdapter.getAllAnnotation(currentartwork);
				  setListAdapter(new AnnotationArrayAdapter(mainActivity.this, R.layout.row_layout, currentAnnotations));
				  artworkLink.loadUrl(serverURL + "information?objectid=" + object[1]);
				  restletAdapter.listFileInFP();
		
			  }
			return false;
	 }

	}
	
	private class LinkViewClientHandler extends WebViewClient {

		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			artworkView.loadUrl(url);
			return true;
	 }
		

	}
	


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentartwork="0";
        currentAnnotations=new AnnotationList();
        current_user_name="testhhh";
	    File f = Environment.getExternalStorageDirectory();
        String filepath = "file:///" + f.getPath() + f.separator + "Neptune" + f.separator
		+ "neptune.html";
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  
        setContentView(R.layout.main);
        artworkView = (WebView)findViewById(R.id.artworkView);
        artworkLink = (WebView)findViewById(R.id.artworkLink);
        artworkLink.setWebViewClient(new LinkViewClientHandler());
        artworkView.setWebViewClient(new WebViewClientHandler());
       	artworkView.getSettings().setJavaScriptEnabled(true);
       	artworkView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        artworkView.loadUrl(closyURL);        
      promptForUserName();
        artworkLink.loadUrl(serverURL + "information");
        annotationButton = (Button)findViewById(R.id.annotationButton); 
        annotationButton.setOnClickListener(btnListener);
        

    }
    
    
    
    //A changer géneraliser l'affichage de l'annotation, on repporte l'affichage a l'annotation elle même
	protected void onListItemClick(ListView l, View v, int position, long id) {
			
		super.onListItemClick(l, v, position, id);
		AnnotationBase currAnnotation = (AnnotationBase)l.getItemAtPosition(position);
		Context mContext = mainActivity.this;
		currAnnotation.showAnnotation(mContext);
						
		}
	
	
	// A changer, on repporte la création de l'annotation à une annotation factory
    private View.OnClickListener btnListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			final CharSequence[] items = {"Ajouter un texte", "Ajouter un enregistrement audio", "Ajouter un enregistrement vid�o"};

			AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity.this);
			builder.setTitle("Choisir le type d'annotation");
			builder.setItems(items, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int item) {
			    	if (item==0) {
			    		AnnoterTexte();
			    	} else if (item==1) {
			    		
			    	} else {
			    		Intent monIntent = new Intent(mainActivity.this,videoRecorder.class);
			    		startActivity(monIntent);

			    	}
			        
			    }
			});
			alert1 = builder.create();
			alert1.show();

		}
			
private void AnnoterTexte(){

			
	        final RestletAdapter restletAdapter = new RestletAdapter();

	        

			Context mContext = mainActivity.this;
			newAnnotationDialog = new Dialog(mContext);
			newAnnotationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			newAnnotationDialog.setContentView(R.layout.addnote);
			newAnnotationDialog.show();
		    newAnnotationTitle = (EditText)newAnnotationDialog.findViewById(R.id.addAnnotationTitle);
		    newAnnotationTitle.setOnEditorActionListener( new OnEditorActionListener() {
				
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					// TODO Auto-generated method stub
		            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
		                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		                in.hideSoftInputFromWindow(v
		                        .getApplicationWindowToken(),
		                        InputMethodManager.HIDE_NOT_ALWAYS);
		                return true;
		            }
					return false;
				}
			});
		    
			newAnnotationBody = (EditText)newAnnotationDialog.findViewById(R.id.addAnnotationBody);
			newAnnotationBody.setOnEditorActionListener( new OnEditorActionListener() {
				
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					// TODO Auto-generated method stub
		            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
		                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		                in.hideSoftInputFromWindow(v
		                        .getApplicationWindowToken(),
		                        InputMethodManager.HIDE_NOT_ALWAYS);
		            return true;
		            }
					return false;
				}
			});
			
			Button cancel = (Button)newAnnotationDialog.findViewById(R.id.CancelAddAnnotationButton);
			Button ok = (Button)newAnnotationDialog.findViewById(R.id.OKAddAnnotationButton);
			cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
				newAnnotationDialog.dismiss();	
				}
			});
			ok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					newAnnotationDialog.dismiss();
					restletAdapter.addAnnotation(new Annotation(0,newAnnotationTitle.getText().toString() , currentartwork, newAnnotationBody.getText().toString(), current_user_name));
			       // fillNotes(currArtwork.artwork_id);
					currentAnnotations = restletAdapter.getAllAnnotation(currentartwork);
					setListAdapter(new AnnotationArrayAdapter(mainActivity.this, R.layout.row_layout, currentAnnotations));		        		

					 // uiHandler.post(updateResult);

				}
			});
			
			// TODO Auto-generated method stub
			
		}		

	};
	
	private void updateMessage()
	{
		Log.w("There is : ",String.valueOf(currentAnnotations.size()));		
		Log.w("Updating artwork : ", currentartwork);

	}
	
	public void promptForUserName()
	{
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Bienvenue dans l'histoire...");
		alert.setMessage("Veuillez entrer votre pseudonyme.");

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  String value = input.getText().toString();
		  current_user_name=value;
		  // Do something with value!
		  }
		});


		alert.show();	}

	
	
	


}
